"""
协程也叫微线程，不是计算机层面的机制，是由程序员人为实现的：
函数之间可以来回切换的执行
-->这种在函数中跳来跳去，只用在io发生等待时才有意义

"""
import asyncio
from time import sleep
from greenlet import greenlet


def func1():
    print(1)
    gr2.switch()
    print(2)
    gr2.switch()


def func2():
    print(3)
    gr1.switch()
    print(4)


gr1 = greenlet(func1)
gr2 = greenlet(func2)


def test_greenlet():
    gr1.switch()


def func11():
    yield 1

    yield from func22()



def func22():
    print(11)
    yield 2
    yield 4
    print(44)


def test_yield1():
    f1 = func11()
    for item in f1:
        print(item)


async def func111():
    print(1)
    await asyncio.sleep(2)
    print(2)


async def func222():
    print(3)
    await asyncio.sleep(2)
    print(4)


def test_async():
    tasks = [
        asyncio.ensure_future(func111()),
        asyncio.ensure_future(func222()),
    ]
    loop = asyncio.get_event_loop()
    loop.run_until_complete(asyncio.wait(tasks))

    """
    协程用于下载等网络处理;遇到结果需要计算，可以把中间结果保存到数据库或文件或队列，
    最后由其它代码和模块来处理pt
    """